/*
 * @Author: Swance
 * @Date: 2024-02-27
 * @Description: 画布导出插件
 */

import { fabric } from 'fabric';
import { IEditor } from '@/types/global';

class ExportPlugin {
  canvas: fabric.Canvas;
  editor: IEditor;
  static pluginName = 'ExportPlugin';
  static apis: string[] = [
    'exportToPNG',
    'exportToSVG',
    'exportToJSON',
    'exportToJPG',
  ];

  constructor(canvas: fabric.Canvas, editor: IEditor) {
    this.canvas = canvas;
    this.editor = editor;
  }

  // 导出为PNG图片
  exportToPNG(fileName: string) {
    const dataURL = this.canvas.toDataURL({
      width: this.canvas.width,
      height: this.canvas.height,
      left: 0,
      top: 0,
      format: 'png',
    });
    const link = document.createElement('a');
    link.download = fileName;
    link.href = dataURL;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  // 导出为JPG图片
  exportToJPG() {
    // canvas 转为 jpeg 之前会移除 alpha 通道，所以透明区域被填充成了黑色，故输出前把 canvas 的背景色改为纯白再输出
    this.canvas.setBackgroundColor('rgb(240, 240, 240)', () => {
      const dataURL = this.canvas.toDataURL({
        width: this.canvas.width,
        height: this.canvas.height,
        left: 0,
        top: 0,
        format: 'jpeg',
      });
      console.log('JPG DataUrl', dataURL);
      this.canvas.setBackgroundColor('', () => {});
    });
  }

  // 导出为SVG
  exportToSVG(fileName: string) {
    const data = this.canvas.toSVG();
    const blob = new Blob([data], { type: 'image/svg+xml' });
    const link = document.createElement('a');
    link.download = fileName;
    link.href = URL.createObjectURL(blob);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  // 导出为JSON
  exportToJSON(fileName: string) {
    const data = JSON.stringify(this.canvas.toJSON());
    const blob = new Blob([data], { type: 'application/json' });
    const link = document.createElement('a');
    link.download = fileName;
    link.href = URL.createObjectURL(blob);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}

export default ExportPlugin;
